package com.ithiema.luence;

import com.itheima.luence.Product;
import com.itheima.luence.ProductUtil;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

public class BatchCreateTmallLuence {
    // 批量创建索引
    @Test
    public void testCreate2() throws Exception{
        // 创建文档的集合
        Document docs = new Document();
        // Collection<Document> docs = new ArrayList<>();
        // 索引目录类,指定索引在硬盘中的位置
        Directory directory = FSDirectory.open(new File("indexDir"));
        // 引入IK分词器
        Analyzer analyzer = new IKAnalyzer();
        // 索引写出工具的配置对象
        IndexWriterConfig conf = new IndexWriterConfig(Version.LATEST, analyzer);
        // 创建索引的写出工具类。参数：索引的目录和配置信息
        IndexWriter indexWriter = new IndexWriter(directory, conf);
        // 设置打开方式：OpenMode.APPEND 会在索引库的基础上追加新索引。OpenMode.CREATE会先清空原来数据，再提交新的索引
        conf.setOpenMode(OpenMode.APPEND);
        List<Product> products = ProductUtil.file2list("140k_products.txt");
        for (Product product : products) {
            docs.add(new TextField("title", product.getName(), Store.YES));
            // 把文档集合交给IndexWriter
            indexWriter.addDocument(docs);
            // 提交
            indexWriter.commit();
        }
        // 关闭
        indexWriter.close();
    }

}
